<template>
  <el-dialog v-dialogDrag title="选择接收人" :visible.sync="visible" :close-on-click-modal="false" width="900px" top="5vh" append-to-body>
    <div class="app-container">
      <el-row :gutter="20">
        <!--部门数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input
              v-model="deptName"
              placeholder="请输入部门名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree highlight-current
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="20" :xs="24">
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户名称"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table ref="dataTable" v-loading="loading" :data="userList" @selection-change="handleSelectionChange"  @select="dialogCheck">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="用户名称" align="center" prop="userName" :show-overflow-tooltip="true" />
            <el-table-column label="用户昵称" align="center" prop="nickName" :show-overflow-tooltip="true" />
            <el-table-column label="部门" align="center" prop="dept.deptName" :show-overflow-tooltip="true" />
            <el-table-column label="手机号码" align="center" prop="phonenumber" width="120" />
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.status == '0' ? 'primary' : 'danger'"
                  disable-transitions
                >{{ scope.row.status == '0' ? '启用' : '停用' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList(2)"
          />
          <div class="dialog-footer" style="margin-top:30px">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="close">取 消</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, exportUser, resetUserPwd, changeUserStatus, importTemplate, deptTreeSelect } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listNoticePlus, getNoticePlus, delNoticePlus, addNoticePlus, updateNoticePlus, exportNoticePlus,saveReceivers,toUsers } from "@/api/pub/noticePlus";


export default {
  name: "selectReceiver",
  components: { Treeselect },
  props: {
    notice: {
      type: Object
    }
  },
  data() {
    return {
      // 选中用户数组
      userIds: [],
      visible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 栏目列表
      categoryOptions: [],
      categoryExpand: false,
      categoryNodeAll: false,
      categoryCheckStrictly: false,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getDeptTree();
    console.log(this.notice)
  },
  methods: {
    show() {
      this.userIds =[];
      this.getList(1);
      this.visible = true;
      this.initSelect(this.userIds, 1);
    },
    /** 查询用户列表 */
    getList(flag) {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          let selectIds = this.userIds;
          this.initSelect(selectIds, flag);
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1 || String(data.id) === value;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList(2);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList(2);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value) {
      let treeList = this.categoryOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.category.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.category.setCheckedNodes(value ? this.categoryOptions: []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.categoryCheckStrictly = value ? true: false;
    },
    /** 提交按钮 */
    submitForm: function() {
      if(this.userIds.length == 0){
        this.msgError("角色id未读到数据!");
        return;
      }
      const data = {
        noticeId: this.notice.id,
        userIds: this.userIds
      };
      saveReceivers(data).then(response => {
        this.msgSuccess("授权成功!");
        this.$emit("close");
        this.visible = false;
      });
    },
    // 多选框选中数据
     handleSelectionChange(selection) {
       if(selection.length == this.userList.length) {
         selection.forEach(item => {
          if (this.userIds.indexOf(item.userId) < 0) {
            this.userIds.push(item.userId);
          }
         });
       }
     },
    dialogCheck: function (selection, row) {
      let selectIds = selection.map((item) => item.userId);
      if (selectIds.indexOf(row.userId) < 0) {
        this.userIds = this.userIds.filter((item) => item != row.userId);
      } else {
        this.userIds.push(row.userId);
      }
    },
    //选中已授权人员
    initSelect(ids, flag) {
      if(flag == 1) {
        //清除所有选中效果
        // this.$refs.dataTable.clearSelection();
        toUsers(this.notice.id).then(response => {
          ids = response.data;
          this.userIds = ids;
          // 根据返回的id对比选中的数据直接勾选上
          response.data.forEach(ele=>{
              this.userList.forEach((ele1,index)=>{
                if(ele==ele1.userId){
                  this.$refs.dataTable.toggleRowSelection(ele1,true);
                };
              });
          });
        });
      } else {
          var that = this;
          that.$nextTick(() => {
            if (ids.length > 0 && this.userList) {
              // 根据返回的id对比选中的数据直接勾选上
              this.userList.forEach((ele1) => {
                if (ids.indexOf(ele1.userId) != -1) {
                  this.$refs.dataTable.toggleRowSelection(ele1,true);
                }
              });
            }
          });
      }

    },
    //关闭弹框
    close(){
      this.$emit("close");
      this.visible = false;
    },
  }
};
</script>
